package com.open.system.handler;



import com.open.system.handler.exception.AcceException;
import com.open.system.handler.exception.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


/**
 * RestControllerAdvice(annotations = {RestController.class})要加上作用范围
 * 不然SpringSecurity无法捕获异常
 */
@Slf4j
@ResponseBody
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class SecurityExceptionHandler {


    public Map<String, Object> send(int code, String message){
        HashMap<String, Object> res = new HashMap<>();
        res.put("code", code);
        res.put("msg", message);
        return res;
    }


    @ExceptionHandler({AuthException.class})
    public Map<String,Object> authException(AuthException e) {
        log.error("登入异常{}", e.getMessage());
        return send(401, e.getMessage());
    }


    @ExceptionHandler({AcceException.class})
    public Map<String,Object> authException(AcceException e) {
        log.error("授权异常{}", e.getMessage());
        return send(403, e.getMessage());
    }

    @ExceptionHandler({DisabledException.class})
    public Map<String,Object> InsertException(DisabledException e) {
        log.error("登入异常{}", e.getMessage());
        return send(400, "该用户已被禁用");
    }


}
